package com.zhiche.wms.service.utils;

import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.domain.model.otm.OtmLocation;
import com.zhiche.wms.domain.model.otm.OtmOrderRelease;
import com.zhiche.wms.domain.model.otm.OtmShipment;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by zhaoguixin on 2018/6/13.
 */
public class OtmShipmentParse {

    private static final Logger logger = LoggerFactory.getLogger(OtmShipmentParse.class);

    public static OtmShipment parse(String xml) throws Exception {
        String rootPath = "/Transmission/TransmissionBody/GLogXMLElement/PlannedShipment/Shipment";
        String shipmentHeaderPath = "/ShipmentHeader";
        OtmShipment otmShipment = new OtmShipment();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Document document = XmlUtil.parseByString(xml);

            //得到根节点
            Element root = (Element) document.selectSingleNode(rootPath + shipmentHeaderPath);

            try {
                Element shipmentGid = root.element("ShipmentGid").element("Gid").element("Xid"); //调度指令号
                if (!Objects.isNull(shipmentGid)) otmShipment.setShipmentGid(shipmentGid.getText());
            } catch (Exception e) {
                logger.info("exception shipmentGid:{}",e.getMessage());
            }
            try {
                Element transactionCode = root.element("TransactionCode");//操作类型
                if (!Objects.isNull(transactionCode)) otmShipment.setTransactionCode(transactionCode.getText());
            } catch (Exception e) {
                logger.info("exception transactionCode:{}",e.getMessage());
            }
            try {
                Element serviceProviderGid = root.element("ServiceProviderGid").element("Gid").element("Xid");//承运商
                if (!Objects.isNull(serviceProviderGid))
                    otmShipment.setServiceProviderGid(serviceProviderGid.getText());
            } catch (Exception e) {
                logger.info("exception serviceProviderGid:{}",e.getMessage());
            }
            try {
                Element transportModeGid = root.element("TransportModeGid").element("Gid").element("Xid");//运输方式
                if (!Objects.isNull(transportModeGid)) otmShipment.setTransportModeGid(transportModeGid.getText());
            } catch (Exception e) {
                logger.info("exception transportModeGid:{}",e.getMessage());
            }
            try {
                Element totalShipUnitCount = root.element("TotalShipUnitCount"); //总数量
                if (!Objects.isNull(totalShipUnitCount)) {
                    int count = Integer.valueOf(totalShipUnitCount.getText());
                    otmShipment.setTotalShipCount(count);
                }
            } catch (Exception e) {
                logger.info("exception totalShipUnitCount:{}",e.getMessage());
            }
            try {
                Element startDt = root.element("StartDt").element("GLogDate"); //发运时间
                    otmShipment.setExpcetShipDate(formatter.parse(startDt.getText()));
            } catch (Exception e) {
                logger.info("exception startDt:{}",e.getMessage());
            }
            try {
                Element endDt = root.element("EndDt").element("GLogDate"); //抵达时间
                if (!Objects.isNull(endDt)) otmShipment.setExpectArriveDate(formatter.parse(endDt.getText()));
            } catch (Exception e) {
                logger.info("exception endDt:{}",e.getMessage());
            }
            try {
                Element driverGid = root.element("DriverGid").element("Gid").element("Xid"); //司机
                if (!Objects.isNull(driverGid)) otmShipment.setDriverGid(driverGid.getText());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Element shipmentType = root.element("FlexFieldStrings").element("Attribute1"); //指令类型
                if (!Objects.isNull(shipmentType)) otmShipment.setShipmentType(shipmentType.getText());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Element trailerNo = root.element("FlexFieldStrings").element("Attribute9"); //挂车号
                if (!Objects.isNull(trailerNo)) otmShipment.setTrailerNo(trailerNo.getText());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Element remark = root.element("FlexFieldStrings").element("Attribute11");//备注
                if (!Objects.isNull(remark)) otmShipment.setRemarks(remark.getText());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Element plateNo = root.element("FlexFieldStrings").element("Attribute12"); //车船号
                if (!Objects.isNull(plateNo)) otmShipment.setPlateNo(plateNo.getText());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Element expectInboundTime = root.element("FlexFieldDates").element("AttributeDate5").element //入库时间
                        ("GLogDate");
                if (!Objects.isNull(expectInboundTime)) otmShipment.setExpectInboundDate(formatter.parse
                        (expectInboundTime.getText()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Element expectReceiptTime = root.element("FlexFieldDates").element("AttributeDate7").element //回单时间
                        ("GLogDate");
                if (!Objects.isNull(expectReceiptTime)) otmShipment.setExpectReceiptDate(formatter.parse
                        (expectReceiptTime.getText()));
            } catch (Exception e) {
                e.printStackTrace();
            }

//            logger.info("otmShipment:{}", otmShipment.toString());

            List<Node> locationNodes = document.selectNodes(rootPath + "/Location");
            List<OtmLocation> otmLocationList = new ArrayList<>();
            for (Node node : locationNodes) {
                if (node.getNodeType() == 1) {
                    Element element = (Element) node;

                    OtmLocation otmLocation = new OtmLocation();
                    try {
                        Element locationGid = element.element("LocationGid").element("Gid").element("Xid"); //地址编码
                        if (!Objects.isNull(locationGid)) otmLocation.setLocationGid(locationGid.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        Element locationName = element.element("LocationName");  //地址名称
                        if (!Objects.isNull(locationName)) otmLocation.setLocationName(locationName.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        Element description = element.element("Description"); //详细地址
                        if (!Objects.isNull(description)) otmLocation.setDescription(description.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        Element zone1 = element.element("Address").element("Zone1"); //省
                        if (!Objects.isNull(zone1)) otmLocation.setZone1(zone1.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        Element zone2 = element.element("Address").element("Zone2"); //市
                        if (!Objects.isNull(zone2)) otmLocation.setZone2(zone2.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        Element zone3 = element.element("Address").element("Zone3"); //县
                        if (!Objects.isNull(zone3)) otmLocation.setZone3(zone3.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    otmLocationList.add(otmLocation);
//                    otmShipment.addLocation(otmLocation);

//                    logger.info("otmLocation:{}", otmLocation.toString());
                }
            }

            List<Node> releaseNodes = document.selectNodes(rootPath + "/Release");
            for (Node node : releaseNodes) {
                if (node.getNodeType() == 1) {
                    Element element = (Element) node;

                    OtmOrderRelease otmRelease = new OtmOrderRelease();

                    try {
                        Element releaseGid = element.element("ReleaseGid").element("Gid").element("Xid");//运输订单号
                        if (!Objects.isNull(releaseGid)) otmRelease.setReleaseGid(releaseGid.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    Element releaseHeader = element.element("ReleaseHeader");
                    if (!Objects.isNull(releaseHeader)) {
                        try {
                            Element cusWaybillNo = releaseHeader.element("ReleaseName");//客户运单号
                            if (!Objects.isNull(cusWaybillNo)) otmRelease.setCusWaybillNo(cusWaybillNo.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element isUrgent = releaseHeader.element("DutyPaid");//是否急发
                            if (!Objects.isNull(isUrgent)) otmRelease.setIsUrgent(isUrgent.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element cusOrderNo = releaseHeader.element("FlexFieldStrings").element("Attribute1");//客户订单号
                            if (!Objects.isNull(cusOrderNo)) otmRelease.setCusOrderNo(cusOrderNo.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element customerId = releaseHeader.element("FlexFieldStrings").element("Attribute2");//客户
                            if (!Objects.isNull(customerId)) otmRelease.setCustomerId(customerId.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element orderAtt = releaseHeader.element("FlexFieldStrings").element("Attribute3");//订单属性
                            if (!Objects.isNull(orderAtt)) otmRelease.setOrderAtt(orderAtt.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element cusTransMode = releaseHeader.element("FlexFieldStrings").element("Attribute4");
                            //客户运输模式分类
                            if (!Objects.isNull(cusTransMode)) otmRelease.setCusTransMode(cusTransMode.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element cusVehicleType = releaseHeader.element("FlexFieldStrings").element("Attribute5");
                            //客户车型
                            if (!Objects.isNull(cusVehicleType)) otmRelease.setCusVehicleType(cusVehicleType.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element vehicleDescribe = releaseHeader.element("FlexFieldStrings").element("Attribute6")
                                    ;//车型描述
                            if (!Objects.isNull(vehicleDescribe))
                                otmRelease.setVehicleDescribe(vehicleDescribe.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element vin = releaseHeader.element("FlexFieldStrings").element("Attribute7");//VIN码
                            if (!Objects.isNull(vin)) otmRelease.setVin(vin.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element modVehicleSize = releaseHeader.element("FlexFieldStrings").element("Attribute8");
                            //改装后的长宽高重
                            if (!Objects.isNull(modVehicleSize)) otmRelease.setModVehicleSize(modVehicleSize.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element stanVehicleType = releaseHeader.element("FlexFieldStrings").element
                                    ("Attribute10");//标准车型
                            if (!Objects.isNull(stanVehicleType))
                                otmRelease.setStanVehicleType(stanVehicleType.getText());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element eptInboundTime = releaseHeader.element("FlexFieldDates").
                                    element("AttributeDate7").element("GLogDate");//要求入库时间
                            if (!Objects.isNull(eptInboundTime)) otmRelease.setExpectInboundDate(formatter.parse
                                    (eptInboundTime.getText()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Element eptReceiptTime = releaseHeader.element("FlexFieldDates").
                                    element("AttributeDate9").element("GLogDate");//要求回单时间
                            if (!Objects.isNull(eptReceiptTime)) otmRelease.setExpectReceiptDate(formatter.parse
                                    (eptReceiptTime.getText()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    try {
                        Element shipFromLocationId = element.element("ShipFromLocationRef").element("LocationRef").
                                element("LocationGid").element("Gid").element("Xid");//起运地编码
                        if (!Objects.isNull(shipFromLocationId))
                            otmRelease.setOriginLocationGid(shipFromLocationId.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        Element shipToLocationId = element.element("ShipToLocationRef").element("LocationRef").
                                element("LocationGid").element("Gid").element("Xid");//目的地编码
                        if (!Objects.isNull(shipToLocationId))
                            otmRelease.setDestLocationGid(shipToLocationId.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        Element earlyPickupDt = element.element("TimeWindow").element("EarlyPickupDt").
                                element("GLogDate");//要求发运时间
                        if (!Objects.isNull(earlyPickupDt)) otmRelease.setExpcetShipDate(formatter.parse
                                (earlyPickupDt.getText()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        Element lateDeliveryDt = element.element("TimeWindow").element("LateDeliveryDt").
                                element("GLogDate");//要求抵达时间
                        if (!Objects.isNull(lateDeliveryDt)) otmRelease.setExpectArriveDate(formatter.parse
                                (lateDeliveryDt.getText()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        Element pickupIsAppt = element.element("TimeWindow").element("PickupIsAppt");//是否超期
                        if (!Objects.isNull(pickupIsAppt)) otmRelease.setPickupIsAppt(pickupIsAppt.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    try {
                        Element isModVehicle = element.element("TimeWindow").element("DeliveryIsAppt");//是否改装车
                        if (!Objects.isNull(isModVehicle)) otmRelease.setIsModVehicle(isModVehicle.getText());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    OtmLocation otmOLocation = selectLocationDTO(otmRelease.getOriginLocationGid(),otmLocationList);

                    otmRelease.setOriginLocationName(otmOLocation.getLocationName());
                    otmRelease.setOriginLocationAddress(otmOLocation.getDescription());
                    otmRelease.setOriginLocationProvince(otmOLocation.getZone1());
                    otmRelease.setOriginLocationCity(otmOLocation.getZone2());
                    otmRelease.setOriginLocationCounty(otmOLocation.getZone3());

                    OtmLocation otmDLocation = selectLocationDTO(otmRelease.getDestLocationGid(),otmLocationList);
                    otmRelease.setDestLocationName(otmDLocation.getLocationName());
                    otmRelease.setDestLocationAddress(otmDLocation.getDescription());
                    otmRelease.setDestLocationProvince(otmDLocation.getZone1());
                    otmRelease.setDestLocationCity(otmDLocation.getZone2());
                    otmRelease.setDestLocationCounty(otmDLocation.getZone3());
                    otmRelease.setShipmentGid(otmShipment.getShipmentGid());

                    otmShipment.addOtmOrderRelease(otmRelease);
                }
            }
            return otmShipment;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 根据地址ID获取地址对象
     * @param locationGid 地址ID
     * @param otmLocationList 地址列表
     * @return
     */
    private static OtmLocation selectLocationDTO(String locationGid,List<OtmLocation> otmLocationList){
        if(StringUtils.isEmpty(locationGid)) throw new BaseException("地址ID为空");
        for (OtmLocation otmLocation:otmLocationList) {
            if (locationGid.equals(otmLocation.getLocationGid())){
                return otmLocation;
            }
        }
        return null;
    }

}
